/**
 * 用户认证状态管理
 * 提供统一的用户登录状态检查和管理功能
 */

class AuthManager {
    constructor() {
        this.token = null;
        this.username = null;
        this.isLoggedIn = false;
        this.validationInProgress = false;
        
        // 初始化时从localStorage读取状态
        this.loadFromStorage();
    }

    /**
     * 从localStorage加载用户状态
     */
    loadFromStorage() {
        this.token = localStorage.getItem('token');
        this.username = localStorage.getItem('username');
        this.isLoggedIn = !!this.token;
        

    }

    /**
     * 保存用户状态到localStorage
     */
    saveToStorage() {
        if (this.token && this.username) {
            localStorage.setItem('token', this.token);
            localStorage.setItem('username', this.username);
        } else {
            localStorage.removeItem('token');
            localStorage.removeItem('username');
        }
    }

    /**
     * 设置用户登录状态
     */
    setLoggedIn(token, username) {
        this.token = token;
        this.username = username;
        this.isLoggedIn = true;
        this.saveToStorage();
        

        
        // 触发登录状态变化事件
        this.triggerAuthStateChange();
    }

    /**
     * 清除用户登录状态
     */
    async logout() {
        try {
            // 调用后端登出接口清除cookie
            await fetch('/api/users/logout', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
        } catch (error) {
            console.error('AuthManager: 登出请求失败', error);
        }
        
        this.token = null;
        this.username = null;
        this.isLoggedIn = false;
        this.saveToStorage();
        

        
        // 触发登录状态变化事件
        this.triggerAuthStateChange();
    }

    /**
     * 验证token有效性
     */
    async validateToken() {
        if (!this.token) {
            return false;
        }

        if (this.validationInProgress) {
            return this.isLoggedIn;
        }

        try {
            this.validationInProgress = true;


            const response = await fetch('/api/users/check', {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + this.token,
                    'Content-Type': 'application/json'
                }
            });

            if (response.ok) {
                const data = await response.json();
                if (data.valid) {
                    this.username = data.username;
                    this.isLoggedIn = true;
                    this.saveToStorage();
                    
                    return true;
                }
            }

            this.logout();
            return false;

        } catch (error) {
            console.error('AuthManager: token验证出错', error);
            this.logout();
            return false;
        } finally {
            this.validationInProgress = false;
        }
    }

    /**
     * 获取当前用户信息
     */
    getCurrentUser() {
        return {
            isLoggedIn: this.isLoggedIn,
            username: this.username,
            token: this.token
        };
    }

    /**
     * 触发认证状态变化事件
     */
    triggerAuthStateChange() {
        const event = new CustomEvent('authStateChanged', {
            detail: this.getCurrentUser()
        });
        document.dispatchEvent(event);
    }

    /**
     * 监听认证状态变化
     */
    onAuthStateChange(callback) {
        document.addEventListener('authStateChanged', (event) => {
            callback(event.detail);
        });
    }

    /**
     * 需要登录时的处理
     */
    requireLogin(redirectUrl = null) {
        if (!this.isLoggedIn) {
            const currentUrl = redirectUrl || window.location.pathname;
            window.location.href = `/login?redirect=${encodeURIComponent(currentUrl)}`;
            return false;
        }
        return true;
    }

    /**
     * 带认证的API请求
     */
    async authenticatedFetch(url, options = {}) {
        if (!this.token) {
            throw new Error('No authentication token available');
        }

        const headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + this.token,
            ...options.headers
        };

        const response = await fetch(url, {
            ...options,
            headers
        });

        // 如果返回401，说明token过期
        if (response.status === 401) {
            this.logout();
            this.requireLogin();
            throw new Error('Authentication expired');
        }

        return response;
    }
}

// 创建全局实例
window.authManager = new AuthManager();

/**
 * 更新导航栏用户状态显示
 */
function updateNavbarUserState(userInfo) {
    const navbarRight = document.querySelector('.unified-navbar-right');
    if (!navbarRight) return;

    if (userInfo.isLoggedIn) {
        // 显示已登录状态
        navbarRight.innerHTML = `
            <span class="unified-nav-item user-info">
                <i class="fas fa-user"></i>
                ${userInfo.username}
            </span>
            <a href="#" class="unified-nav-item" onclick="handleLogout()">
                <i class="fas fa-sign-out-alt"></i>
                退出
            </a>
        `;
    } else {
        // 显示未登录状态
        navbarRight.innerHTML = `
            <a href="/login" class="unified-nav-item">
                <i class="fas fa-sign-in-alt"></i>
                登录
            </a>
            <a href="/register" class="unified-nav-item">
                <i class="fas fa-user-plus"></i>
                注册
            </a>
        `;
    }
}

/**
 * 处理用户退出
 */
async function handleLogout() {
    if (confirm('确定要退出登录吗？')) {
        await window.authManager.logout();
        window.location.href = '/';
    }
}

/**
 * 页面加载时初始化认证状态
 */
document.addEventListener('DOMContentLoaded', async function() {

    
    // 监听认证状态变化
    window.authManager.onAuthStateChange(updateNavbarUserState);
    
    // 验证当前token状态
    await window.authManager.validateToken();
    
    // 更新导航栏显示
    updateNavbarUserState(window.authManager.getCurrentUser());
});

// 导出给其他脚本使用
window.AuthManager = AuthManager; 